<template>
      <div ref="graphChart" style="width: 100%; height: 100%"></div>
</template>
<script>
export default {
  name: "Graph1",
  props: {
    graphData: {
      type: Array,
      required: true,
      default: () => [],
    },
  },
  data() {
    return {
      chart: null,
    };
  },
  mounted() {
    console.log(this.graphData);
    this.initChart();
    this.processData();

    // 监听窗口大小变化
    window.addEventListener("resize", this.handleResize);
  },
  watch: {
    graphData: {
      handler(newVal) {
        if (newVal && newVal.length > 0) {
          if (this.chart) {
            this.chart.dispose();
          }
          this.initChart();
          this.processData();
        }
      },
      deep: true,
    },
  },
  methods: {
    handleResize() {
      if (this.chart) {
        this.chart.resize();
      }
    },
    initChart() {
      // 初始化ECharts实例
      this.chart = this.$echarts.init(this.$refs.graphChart);
    },
    processData() {
      this.processDataWithData(this.graphData);
    },
    processDataWithData(data) {
      if (!data || !Array.isArray(data) || data.length === 0) {
        console.warn("Graph data is empty or invalid");
        return;
      }

      // 收集所有节点和边
      const allNodes = new Map();
      const allLinks = new Map();

      data.forEach((item) => {
        // 处理节点
        if (item.all_nodes_in_path) {
          const firstNodeId = String(item.all_nodes_in_path[0].id);
          const lastNodeId = String(
            item.all_nodes_in_path[item.all_nodes_in_path.length - 1].id
          );

          item.all_nodes_in_path.forEach((node, idx) => {
            const nodeId = String(node.id);
            if (!allNodes.has(nodeId)) {
              const nodeObj = {
                id: nodeId,
                name: this.getNodeName(node),
                symbolSize: this.getNodeSize(node),
                category: this.getNodeCategory(node),
                itemStyle: {
                  color: this.getNodeColor(node),
                },
                label: {
                  show: true,
                  position: "right",
                  fontSize: 12,
                },
                // 添加原始数据用于tooltip
                originalData: node,
              };
              if (nodeId === firstNodeId) {
                nodeObj.x = 200;
                nodeObj.y = 300;
                nodeObj.fixed = true;
              } else if (nodeId === lastNodeId) {
                nodeObj.x = 1000;
                nodeObj.y = 300;
                nodeObj.fixed = true;
              }
              allNodes.set(nodeId, nodeObj);
            }
          });
        }

        // 处理边
        if (item.all_relationships_in_path) {
          item.all_relationships_in_path.forEach((rel) => {
            const source = String(rel.start);
            const target = String(rel.end);
            const linkKey = `${source}-${target}`;
            if (!allLinks.has(linkKey)) {
              allLinks.set(linkKey, {
                source,
                target,
                value: rel.type,
                lineStyle: {
                  color: "#666",
                  width: 2,
                },
                label: {
                  show: true,
                  fontSize: 10,
                  color: "#333",
                },
                // 添加原始数据用于tooltip
                originalData: rel,
              });
            }
          });
        }
      });

      const nodes = Array.from(allNodes.values());
      const links = Array.from(allLinks.values());

      console.log(nodes);
      console.log(links);
      console.log(
        "node ids:",
        nodes.map((n) => n.id)
      );
      console.log(
        "link sources:",
        links.map((l) => l.source)
      );
      console.log(
        "link targets:",
        links.map((l) => l.target)
      );

      // 创建分类
      const categories = this.createCategories(nodes);

      // 配置图表选项
      const option = {
        title: {
          text: "关系图谱",
          left: "center",
          textStyle: {
            fontSize: 18,
            fontWeight: "bold",
          },
        },
        tooltip: {
          formatter: function (params) {
            if (params.dataType === "node") {
              const node = params.data.originalData;
              let tooltipText = `${params.data.name}<br/>类型: ${params.data.category}`;

              // 添加更多详细信息
              if (node.value) {
                Object.keys(node.value).forEach((key) => {
                  if (
                    key !== "name" &&
                    key !== "Title" &&
                    key !== "Ip" &&
                    key !== "HostPortId"
                  ) {
                    tooltipText += `<br/>${key}: ${node.value[key]}`;
                  }
                });
              }

              return tooltipText;
            } else {
              const link = params.data.originalData;
              return `关系类型: ${params.data.value}<br/>起始节点: ${link.start}<br/>目标节点: ${link.end}`;
            }
          },
        },
        // legend: {
        //     data: categories.map(cat => cat.name),
        //     orient: 'vertical',
        //     left: 'left',
        //     top: 'middle'
        // },
        animationDurationUpdate: 1500,
        animationEasingUpdate: "quinticInOut",
        series: [
          {
            type: "graph",
            layout: "force",
            data: nodes,
            links: links,
            categories: categories,
            roam: true,
            focusNodeAdjacency: true,
            draggable: true,
            label: {
              show: true,
              position: "right",
            },
            force: {
              repulsion: 200,
              edgeLength: 150,
              gravity: 0.05,
            },
            emphasis: {
              focus: "adjacency",
              lineStyle: {
                width: 4,
              },
            },
          },
        ],
      };

      // 渲染图表
      this.chart.setOption(option);
    },
    getNodeName(node) {
      // 根据节点类型获取显示名称
      if (node.value.name) {
        return node.value.name;
      } else if (node.value.Title) {
        return node.value.Title;
      } else if (node.value.Ip) {
        return node.value.Ip;
      } else if (node.value.HostPortId) {
        return node.value.HostPortId;
      } else {
        return `节点${node.id}`;
      }
    },
    getNodeSize(node) {
      // 根据节点类型设置大小
      const label = node.labels[0];
      switch (label) {
        case "Org":
          return 35;
        case "Title":
          return 28;
        case "HostPort":
          return 22;
        case "Ip":
          return 18;
        default:
          return 25;
      }
    },
    getNodeCategory(node) {
      // 根据节点类型设置分类
      const label = node.labels[0];
      switch (label) {
        case "Org":
          return "组织";
        case "Title":
          return "标题";
        case "HostPort":
          return "主机端口";
        case "Ip":
          return "IP地址";
        default:
          return "其他";
      }
    },
    getNodeColor(node) {
      // 根据节点类型设置颜色
      const label = node.labels[0];
      switch (label) {
        case "Org":
          return "#ff7875";
        case "Title":
          return "#69c0ff";
        case "HostPort":
          return "#95de64";
        case "Ip":
          return "#ffd666";
        default:
          return "#b37feb";
      }
    },
    createCategories(nodes) {
      // 创建分类数组
      const categories = [];
      const categorySet = new Set();

      nodes.forEach((node) => {
        if (!categorySet.has(node.category)) {
          categorySet.add(node.category);
          categories.push({
            name: node.category,
          });
        }
      });

      return categories;
    },
  },
  beforeDestroy() {
    // 销毁图表实例
    if (this.chart) {
      this.chart.dispose();
    }
    // 移除事件监听器
    window.removeEventListener("resize", this.handleResize);
  },
};
</script>
<style scoped></style>
